import { Injectable, Logger } from '@nestjs/common';
import { SchedulerRegistry } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { CronJob } from 'cron';
import Email from '../utils/emailsend';
import { UserTask } from './dto/task.entity';
import { Repository } from 'typeorm';
import { NoteService } from '../note-data/note.service';

@Injectable()
export class TaskService {
  private cronTask: any;
  private emailData = new Email();
  private readonly logger = new Logger(TaskService.name + '定时任务');
  constructor(
    private readonly schedulerRegistry: SchedulerRegistry,
    @InjectRepository(UserTask)
    private readonly taskServiceRepository: Repository<UserTask>,
    private readonly noteService: NoteService,
  ) {
    // this.startCronJob('7', new Date('2024-05-04 15:48:10'));
    // this.startCronJob('Leon', new Date('2024-05-03 19:00:40'));
    this.getCrons();
  }

  async createTask(userTask: UserTask) {
    const task = new UserTask();
    task.email = userTask.email;
    task.noteId = userTask.noteId;
    task.sendTime = userTask.sendTime;
    task.taskName = userTask.taskName;
    task.taskUserName = userTask.taskUserName;
    task.createTime = userTask.createTime;
    task.taskState = userTask.taskState;
    task.remarks = userTask.remarks;
    return await this.taskServiceRepository.save(task);
  }

  async deleteTask(id: string) {
    return await this.taskServiceRepository.delete(id);
  }

  async setTaskState(id: any, taskState: string) {
    return await this.taskServiceRepository.update(id, {
      taskState,
    });
  }

  async findTask(id: any) {
    return await this.taskServiceRepository.findOne({
      where: {
        id,
      },
    });
  }

  async getTaskList(user: any) {
    if (user.id === '22') {
      return await this.taskServiceRepository.find({
        order: { createTime: 'DESC' },
      });
    }
    const taskList = await this.taskServiceRepository.find({
      where: {
        taskUserName: user.username,
      },
      order: { createTime: 'DESC' },
    });
    return taskList;
  }

  async startCronJob(jobName: string, time: Date) {
    this.cronTask = null;
    this.cronTask = new CronJob(new Date(time), async () => {
      const task = await this.findTask(jobName);
      const noteData = await this.noteService.findNote(task.noteId);

      try {
        await this.setTaskState(Number(jobName), 'success');
        // 发送成功后 状态改为 success
        await this.emailData.send({
          from: 'aliangnice@163.com',
          to: task.email,
          subject: noteData.title,
          // text: noteData.text,
          html: `<div style="background-color:#ECECEC; padding: 35px;">
          <table cellpadding="0" align="center"
                 style="width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;">
              <tbody>
              <tr>
                  <th valign="middle"
                      style="height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #49bcff; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;">
                      <font face="微软雅黑" size="5" style="color: rgb(255, 255, 255); ">Aspiration</font>
                  </th>
              </tr>
              <tr>
                  <td>
                      <div style="padding:25px 35px 40px; background-color:#fff;">
                          <h2 style="margin: 5px 0px; ">
                              <font color="#333333" style="line-height: 20px; ">
                                  <font style="line-height: 22px; " size="4">
                                      亲爱的 ${task.taskUserName}</font>
                              </font>
                          </h2>
                          <P>${noteData.title}</P>
                          <p>下面是您的信息</P>
                            <p>${noteData.text}</p>
                            <p align="right">${task.remarks}</p>
                          <p align="right">${task.sendTime}</p>
                          <div style="width:700px;margin:0 auto;">
                              <div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
                                  <p>此为系统邮件，请勿回复<br>
                                      请保管好您的邮箱，避免账号被他人盗用
                                  </p>
                              </div>
                          </div>
                      </div>
                  </td>
              </tr>
              </tbody>
          </table>
      </div>
      `,
        });
        await this.deleteCron(jobName);
      } catch (error) {
        console.info(error);
        await this.setTaskState(Number(jobName), 'error');
        this.deleteCron(jobName);
      }
    });
    this.schedulerRegistry.addCronJob(jobName, this.cronTask);
    this.cronTask.start();
    this.setTaskState(Number(jobName), 'loading');
    this.logger.debug(`cron ${jobName} executed`);
  }
  async deleteCron(jobName: string) {
    const result = this.schedulerRegistry.deleteCronJob(jobName);
    this.logger.warn(`job ${jobName} deleted!`);
    return result;
  }

  getCronList() {
    const jobs = this.schedulerRegistry.getCronJobs();
    return jobs.size;
  }
  getCrons() {
    const jobs = this.schedulerRegistry.getCronJobs();
    jobs.forEach((value, key) => {
      let next = null;
      try {
        next = value.nextDates();
      } catch (e) {
        next = 'error: next fire date is in the past!';
      }
      this.logger.debug(`job: ${key} -> next: ${next}`);
    });
  }
}
